package com.softaria.gwt.common.client.widget;

import com.google.gwt.animation.client.Animation;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;

/**
 * A custom animation that moves a small image around a circle in an
 * {@link AbsolutePanel}.
 */
public class CircleAnimation extends Animation {
  private static final String IMAGE_CIRCLE_ANIMATION = "/images/circle_animation.png";
  private AbsolutePanel absolutePanel;
  private Widget animateeBottom;
  private Widget animateeLeft;
  private Widget animateeRight;
  private Widget animateeTop;
  private int centerX = 50;
  private int centerY = 50;
  private int radius = 25;

  public CircleAnimation(AbsolutePanel panel, int centerX, int centerY) {
    absolutePanel = panel;

    this.centerX = centerX;
    this.centerY = centerY;
    // this.radius = radius;

    animateeTop = getImage();
    animateeBottom = getImage();
    animateeLeft = getImage();
    animateeRight = getImage();
    absolutePanel.add(animateeTop);
    absolutePanel.add(animateeBottom);
    absolutePanel.add(animateeLeft);
    absolutePanel.add(animateeRight);
    onComplete();

    run(3000);
  }

  @Override
  protected void onUpdate(double progress) {
    double radian = 2 * Math.PI * progress;
    updatePosition(animateeLeft, radian, 0);
    updatePosition(animateeBottom, radian, 0.5 * Math.PI);
    updatePosition(animateeRight, radian, Math.PI);
    updatePosition(animateeTop, radian, 1.5 * Math.PI);
  }

  private void updatePosition(Widget w, double radian, double offset) {
    radian += offset;
    double x = radius * Math.cos(radian) + centerX;
    double y = radius * Math.sin(radian) + centerY;
    absolutePanel.setWidgetPosition(w, (int) x, (int) y);
  }

  private HTML getImage() {
    return new HTML("<nobr><span class=\"" + GWT.getModuleBaseURL() + IMAGE_CIRCLE_ANIMATION
        + "\"><span class=\"sa-animation-icon\">" + "&nbsp;" + "</span></span></nobr>");
  }
}
